
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  calculation;

import java.util.Hashtable;

import logger.PoolLogger;

import operations.Operation;


import utility.ReadFile;
import control.SpecialCharacter;
import database.RecordSearch;
import dbmanager.Column;
import dbmanager.DBManager;
import dbmanager.GetIdName;

public class Expressionsubstring 
{
	String Operator = "Operation"; 
	SpecialCharacter cp;
	boolean FLAG = false;
	int beginIndex=0;
	int endIndex=0;
	String Result="";
	ReadFile rFile = new ReadFile();
	GetIdName gin; 
	Operation operation;
	
	String Right;
	String Left;
	
	Hashtable<Object,Object> TransactionMap = new Hashtable<Object,Object>(); 
	Hashtable<Object,Object>TransactionDetailMap =  new Hashtable<Object,Object>();
	
	PoolLogger pl;
	
	Expressionsubstring(Hashtable<Object,Object> TransactionMap, Hashtable<Object,Object>TransactionDetailMap)
	{
		cp = new SpecialCharacter();
		
		this.TransactionMap.putAll(TransactionMap);
		this.TransactionDetailMap.putAll(TransactionDetailMap);
		
		// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
	}
	
	public String getResult(String expression, String [] RecordSet) 
	{	
		String path = rFile.getMasterReportPath();
		String copyExpression = expression;
		for(int i= 0;i<RecordSet.length;i++)
		{
			if(expression.contains(RecordSet[i]))
			{
				int index = expression.indexOf(RecordSet[i]);
				
				int begin = cp.getPrevSpChar(index, expression.toCharArray());
				
				if(begin==-1) 
					begin++;
				beginIndex = begin;
				Left = expression.substring(begin,index);
				try
				{
					FLAG = true;
					Double.parseDouble(Left);
					Left = expression.substring(begin,index);
				}
				catch (Exception e) 
				{
					FLAG = false;
				}
				if(FLAG == false)
				{
					Left = Left.substring(1);
					int tabbegin = cp.getPrevSpChar(begin, expression.toCharArray());
					if(tabbegin==-1) 
						tabbegin++;
					String LeftTable = expression.substring(tabbegin,begin);
					
					System.out.println("calculation::Expressionsubstring::getResult():Left : "+Left);
					pl.info("calculation::Expressionsubstring::getResult():Left : "+Left);
					pl.debug("calculation::Expressionsubstring::getResult():Left : "+Left);
					pl.warn("calculation::Expressionsubstring::getResult():Left : "+Left);
					pl.fatal("calculation::Expressionsubstring::getResult():Left : "+Left);
					pl.error("calculation::Expressionsubstring::getResult():Left : "+Left);
					pl.trace("calculation::Expressionsubstring::getResult():Left : "+Left);
					
					System.out.println("calculation::Expressionsubstring::getResult():LeftTable : "+LeftTable);
					pl.info("calculation::Expressionsubstring::getResult():LeftTable : "+LeftTable);
					pl.debug("calculation::Expressionsubstring::getResult():LeftTable : "+LeftTable);
					pl.warn("calculation::Expressionsubstring::getResult():LeftTable : "+LeftTable);
					pl.fatal("calculation::Expressionsubstring::getResult():LeftTable : "+LeftTable);
					pl.error("calculation::Expressionsubstring::getResult():LeftTable : "+LeftTable);
					pl.trace("calculation::Expressionsubstring::getResult():LeftTable : "+LeftTable);
					
					beginIndex = tabbegin;
					
					if(LeftTable.equals("transaction_details"))
						Left = TransactionDetailMap.get(Left.toLowerCase()).toString();
					else if(LeftTable.equals("transaction"))
						Left = TransactionMap.get(Left.toLowerCase()).toString();
					System.out.println("calculation::Expressionsubstring::getResult():LeftValue : "+Left);
					pl.info("calculation::Expressionsubstring::getResult():LeftValue : "+Left);
					pl.debug("calculation::Expressionsubstring::getResult():LeftValue : "+Left);
					pl.warn("calculation::Expressionsubstring::getResult():LeftValue : "+Left);
					pl.fatal("calculation::Expressionsubstring::getResult():LeftValue : "+Left);
					pl.error("calculation::Expressionsubstring::getResult():LeftValue : "+Left);
					pl.trace("calculation::Expressionsubstring::getResult():LeftValue : "+Left);
					
				}
				
				int tabbegin = cp.getNextSpChar(index, expression.toCharArray());
				String RightTable = expression.substring(index+1,tabbegin);
				endIndex = tabbegin;
				
				try
				{
					FLAG = true;
					Double.parseDouble(RightTable);
					Right = RightTable;
				}
				catch (Exception e) 
				{
					FLAG = false;
				}
				if(FLAG == false)
				{
					int end = cp.getNextSpChar(tabbegin, expression.toCharArray());
					Right = expression.substring(tabbegin+1,end);
					
					System.out.println("calculation::Expressionsubstring::getResult():RightTable : "+RightTable);
					pl.info("calculation::Expressionsubstring::getResult():RightTable : "+RightTable);
					pl.debug("calculation::Expressionsubstring::getResult():RightTable : "+RightTable);
					pl.warn("calculation::Expressionsubstring::getResult():RightTable : "+RightTable);
					pl.fatal("calculation::Expressionsubstring::getResult():RightTable : "+RightTable);
					pl.error("calculation::Expressionsubstring::getResult():RightTable : "+RightTable);
					pl.trace("calculation::Expressionsubstring::getResult():RightTable : "+RightTable);
					
					System.out.println("calculation::Expressionsubstring::getResult():Right : "+Right);
					pl.info("calculation::Expressionsubstring::getResult():Right : "+Right);
					pl.debug("calculation::Expressionsubstring::getResult():Right : "+Right);
					pl.warn("calculation::Expressionsubstring::getResult():Right : "+Right);
					pl.fatal("calculation::Expressionsubstring::getResult():Right : "+Right);
					pl.error("calculation::Expressionsubstring::getResult():Right : "+Right);
					pl.trace("calculation::Expressionsubstring::getResult():Right : "+Right);
					
					endIndex = end;
					if(RightTable.equals("transaction_details"))
						Right = TransactionDetailMap.get(Right.toLowerCase()).toString();
					else if(RightTable.equals("transaction"))
						Right = TransactionMap.get(Right.toLowerCase()).toString(); 
					System.out.println("calculation::Expressionsubstring::getResult():RightValue : "+Right);
					pl.info("calculation::Expressionsubstring::getResult():RightValue : "+Right);
					pl.debug("calculation::Expressionsubstring::getResult():RightValue : "+Right);
					pl.warn("calculation::Expressionsubstring::getResult():RightValue : "+Right);
					pl.fatal("calculation::Expressionsubstring::getResult():RightValue : "+Right);
					pl.error("calculation::Expressionsubstring::getResult():RightValue : "+Right);
					pl.trace("calculation::Expressionsubstring::getResult():RightValue : "+Right);					
				}
				
				//CALL OPERATIONS
				
				//Get CLASS NAME FROM THE OPERATOR
				String operator_id = gin.getId(Operator);
				RecordSearch rs =new RecordSearch(); 
				Hashtable<Object, Object> table =new Hashtable<Object, Object>();
				table.put("td", "null");
				table.put("mid", operator_id);
				rs.setConditionMap(table);
				String record = rFile.searchObject(rs.getArrayFromResultSet(),gin.getId(RecordSet[i]));
				if(record.equals("error"))
					return "error";
				else
				{
					String temp [] = record.split("\t");
					
					//Get ORDER OF VALUE TEXT
					try
					{
						//RandomAccessFile raf = new RandomAccessFile(path,"r");
						//FileUtility file = new FileUtility(raf);
						//int VTOrder =file.getColumnIndex("VT")-1;
						int VTOrder = Column.vt_index-1;
						operator_id = temp[VTOrder];
						Class c = Class.forName("operations."+operator_id);
						operation = (Operation) c.newInstance();
						expression = operation.operation(Left, Right);
					}
					catch (ClassNotFoundException e) 
					{	
						System.out.println("calculation::Expressionsubstring::getResult():Exception -> Class Not Found : "+operator_id);
						pl.info("calculation::Expressionsubstring::getResult():Exception -> Class Not Found : "+operator_id);
						pl.debug("calculation::Expressionsubstring::getResult():Exception -> Class Not Found : "+operator_id);
						pl.warn("calculation::Expressionsubstring::getResult():Exception -> Class Not Found : "+operator_id);
						pl.fatal("calculation::Expressionsubstring::getResult():Exception -> Class Not Found : "+operator_id);
						pl.error("calculation::Expressionsubstring::getResult():Exception -> Class Not Found : "+operator_id);
						pl.trace("calculation::Expressionsubstring::getResult():Exception -> Class Not Found : "+operator_id);
					} catch (InstantiationException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} 
					
				}
			}
		}
		//System.out.println("calculation::Expressionsubstring::getResult():beginIndex : "+beginIndex);
		//System.out.println("calculation::Expressionsubstring::getResult():endIndex : "+endIndex);
		if(expression.equals(copyExpression))
		{
			return "error";
		}
		if(copyExpression.length() != endIndex)
		{
			StringBuffer temp = new StringBuffer(copyExpression);
			temp.replace(beginIndex, endIndex, expression);
			expression = getResult(temp.toString(), RecordSet);
		}
		try
		{
			Double.parseDouble(expression);
			return expression;
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		
		System.out.println("calculation::Expressionsubstring::getResult():Result is : "+Result);
		pl.info("calculation::Expressionsubstring::getResult():Result is : "+Result);
		pl.debug("calculation::Expressionsubstring::getResult():Result is : "+Result);
		pl.warn("calculation::Expressionsubstring::getResult():Result is : "+Result);
		pl.fatal("calculation::Expressionsubstring::getResult():Result is : "+Result);
		pl.error("calculation::Expressionsubstring::getResult():Result is : "+Result);
		pl.trace("calculation::Expressionsubstring::getResult():Result is : "+Result);
		return expression;
	}
}
